import { Component, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChange } from "@angular/core";
import { FileItem, FileLikeObject, FileUploader, ParsedResponseHeaders } from "ng2-file-upload";
import { MyhttpService } from "../myhttp.service";
import { CommService } from "../comm-service";

declare var $: any;

@Component({
  selector: "form-file-input",
  template: `
    <!--触发点击选择文件用的，隐藏-->
    <input class="form-control ngselectFileInput" type="file" ng2FileSelect [uploader]="uploader"
           (change)="selectedFileOnChanged($event)"/>

    <!--显示和操作用的（触发选择的是点击事件在 .ngselectFileInput上），文件选择input+ button-->
    <div class="row">
      <div [ngClass]="{'col-lg-12':autoup,'col-lg-10':!autoup}">
        <div class="input-group selectFile">
          <div class="input-icon" id="selectFileInput">
            <input class="form-control" type="text" name="filename" readonly
                   [value]="filename">
          </div>
          <span class="input-group-btn">
              <button class="btn btn-success" type="button"><i class="fa fa-file"></i> 选择</button>
          </span>
        </div>
      </div>
      <div class="col-lg-1">
        <button *ngIf="!autoup" class="btn btn-info" type="button" (click)="importDone()"
                [disabled]="drbtnDisabled">导入
        </button>
      </div>
    </div>
    <!--公用组件的 提示信息（附件类型限制类，附件大小限制类，必填与否需要在具体的使用表单中做控制）+ 进度条的处理位置-->
    <div class="row">
      <div [ngClass]="{'col-lg-12':autoup,'col-lg-10':!autoup}">
        <div class="tsroom">
          <span class="text-danger" *ngIf="warntextflag">{{warntext}}</span>
          <div *ngIf="progressFlag" class="myprogress">
            <div class="myprogress-bar" [style.width]="progressbarLeft"></div>
            <div class="jdtext" [style.left]="progressbarLeft"><span>{{jdtext}}</span></div>
          </div>
        </div>
      </div>
    </div>
    <div class="hxfileroom" *ngIf="fileshow">
      <div class="imgroom" *ngIf="filelx==='tp'">
        <img [src]="filepath" width="100%" height="100%"/>
      </div>
    </div>
  `,
  styles: [
    ".ngselectFileInput{display: none}",
    // 提示
    ".tsroom{text-align: center;margin-top: 10px;width: 100%}",
    ".myprogress{width: calc(100% - 100px);height: 20px;background-color: #090a0b;position: relative}",
    ".myprogress-bar{position: absolute;height: 20px;background-color: #3598dc;left: 0px;top: 0px;}",
    ".jdtext{position: absolute;top: 0px;left: 0px;width: 100px}",
    //回显
    ".hxfileroom{width: 100px;height: 100px}",
    ".hxfileroom>.imgroom{width: 100%;height: 100%}"
  ]
})
export class FormFileiinput implements OnInit, OnChanges {
  // 是否自动上传
  autoup: boolean; // 是否自动上传
  drbtnDisabled: boolean = true; // 导入按钮是否可点击
  uploadurl: string = "manager/attachment/uploadAttachment"; //上传的remote路径。
  uploadForm: any = {
    attachmentDefineId: 1  // uploadurl使用默认值的时候，1===照片  2=其他
  };   // 根据 uploadurl 是否使用默认值，有不同的值

  nowfile: FileItem;

  // 回显处理
  filename: string = "";
  filelx: string = ""; // 文件的类型，回显格式不同
  fileshow: boolean = false; // 控制回显
  filepath: string = ""; // 回显路径


  uploader: FileUploader;
  // 附件类型限制类警告，附件大小限制类，必填与否需要在具体的使用表单中做控制
  warntextflag: boolean = false;
  warntext: string = "";
  // 进度条容器
  progressFlag: boolean = false;  // 进度条容器是否显示
  progressbarLeft: string = "0px";
  jdtext: string = "";


  initUploader(): void {
    const filealias = this.o.filealias ? this.o.filealias : "file";
    this.uploader = new FileUploader({
      url: `${this.commservice.uploadFileurl}${this.uploadurl}`,
      method: "POST",
      itemAlias: filealias,
      autoUpload: this.autoup,//选择文件后，不自动上传
    });
    const pubheaderparams1 = this.commservice.getpubheaderParams1(null);
    const pubheaderparams2 = this.commservice.getpubheaderParams2();
    this.uploader.setOptions({
      headers: [{
        name: "xc_client_sessionid",
        value: pubheaderparams1.signkey
      }, {
        name: "Content-Signature",
        value: pubheaderparams1.signreqobj
      }, {
        name: 'xc_sso_sessionid',
        value: pubheaderparams2.access_token
      }, {
        name: "Authorization",
        value: pubheaderparams2.Authorization
      }],
      allowedFileType: this.o.allowedFileType,
    });
  }


  initUploaderEvents() {
    this.uploader.onBuildItemForm = this.buildItemForm.bind(this);
    this.uploader.onAfterAddingFile = this.afterAddFile.bind(this);
    this.uploader.onWhenAddingFileFailed = this.whenAddFileFailed.bind(this);
    this.uploader.onProgressItem = this.onProgress.bind(this);
    this.uploader.onSuccessItem = this.successItem.bind(this);
  }

  buildItemForm(fileItem: FileItem, form: any): void {
    if (this.uploadForm) {
      for (let key in this.uploadForm) {
        form.append(key, this.uploadForm[key]);
      }
    }
  }

  selectedFileOnChanged(e: any): void {

  }

  /**
   * 选择完文件后的回调
   * @param {FileItem} file
   */
  afterAddFile(file: FileItem): void {
    this.filename = file.file.name; //  选择的文件的名称
    this.progressFlag = false; // 进度还原
    this.fileshow = false; //附件回显还原
    this.filepath = "";
    this.warntextflag = false; // 警告信息还原
    this.warntext = "";
    if (!this.o.autoup) {
      this.drbtnDisabled = true;
    }

    if (this.o.limtsize) {
      const filesize = file.file.size;
      if (filesize > this.o.limtsize * 1024 * 1024) {
        this.outMethod.emit({
          fileId: "",
          filepath: "",
          flag: "fail",
          msg: `图片大小超过${this.o.limtsize}M`
        });
        this.warntextflag = true;
        this.warntext = "图片大小超过了" + this.o.limtsize + "M";
        return;
      }
    }
    if (this.o.addurl) {
      // 非默认服务
      this.fileshow = false;
      if (this.autoup) {
        // 自动上传
        this.uploader.uploadItem(file);
        this.progressFlag = true;
      } else {
        //  非自动上传
        this.nowfile = file;
        this.drbtnDisabled = false;
        this.progressFlag = false;
      }
    } else {
      // 默认服务
      if (this.autoup) {
        // 自动上传
        this.uploader.uploadItem(file);
        this.progressFlag = true;
        if (this.o.attachmentDefineId == 1) {
          this.fileshow = true;
        } else {
          this.fileshow = false;
        }
      } else {
        // 非自动上传
        this.nowfile = file;
        this.drbtnDisabled = false;
        this.progressFlag = false;
        if (this.o.attachmentDefineId == 1) {
          this.fileshow = true;
        } else {
          this.fileshow = false;
        }
      }
    }
  }

  /**
   * 选择文件失败的回调
   * @param {FileLikeObject} item
   * @param filter
   * @param options
   */
  whenAddFileFailed(item: FileLikeObject, filter: any, options: any): void {
    this.filename = "";
    this.progressFlag = false;
    this.fileshow = false;
    this.filepath = "";
    this.warntextflag = true;
    this.warntext = "附件类型不合法";
    if (!this.o.autoup) {
      this.drbtnDisabled = true;
    }
    const outobj = {
      fileId: "",
      filepath: "",
      flag: "fail",
      msg: "文件类型不正确，请上传," + this.o.allowedFileType.toString() + ",类型文件"
    };
    // this.outMethod.emit(outobj);
  }

  /**
   * 非自动上传点击上传
   */
  importDone(): void {
    this.commservice.myswal("warning", "确定导入该文件?", "", "cz", () => {
      this.commservice.blockUI({
        boxed: true,
        message: "上传中...",
        zIndex: 10051,
        overlayColor: "#67809F"
      });
      if (this.nowfile) {
        this.uploader.uploadItem(this.nowfile);
        this.progressFlag = true;
      }
    });
  }


  /**
   * 上传进度
   * @param {FileItem} fileItem  上传的文件
   * @param progress     该文件的上传进度
   * @returns {any}
   */
  onProgress(fileItem: FileItem, progress: any): any {
    //console.log("文件上传进度", progress);
    let totallenth = 300;
    if ($(".myprogress").length) {
      totallenth = $(".myprogress").width();
    }
    this.progressbarLeft = progress / 100 * totallenth + "px";
    if (progress == 0) {
      this.jdtext = "开始上传";
    } else if (progress == 100) {
      this.jdtext = "上传完成";
      this.progressFlag = false;
    } else {
      this.jdtext = progress + "%";
    }
  }

  /**
   * 上传成功后 的回调
   * @param {FileItem} item
   * @param {string} response
   * @param {number} status
   * @param {ParsedResponseHeaders} headers
   */
  successItem(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders): void {
    if (status == 200) {
      const respbody = JSON.parse(response);
      const ywcode = respbody.code; // 业务接口code 【8001(signkey 失效)】,【 200】【其他的失败直接抛出 message】
      const ywmsg = respbody.message; // 业务接口提示信息
      const ywresult = respbody.result;// 业务接口返回的数据
      if (ywcode === 8001) {
        // 【signkey 失效】， 重新获取signkey 并且 重新请求
        // 改写返回中的code值
        respbody.code = 202;
      }
      if (this.o.addurl) {
        // 非默认服务，非自动导入的上传效果去掉。 自动上传的没有上传效果
        this.commservice.unblockUI(false);
        const retobj: any = {};
        if (ywcode == 200) {
          retobj['flag'] = "success";
          retobj["msg"] = "上传成功";
          retobj["servemsg"] = ywmsg;
          retobj["result"] = ywresult;
          this.outMethod.emit(retobj);
        } else {
          retobj['flag'] = "fail";
          retobj["msg"] = "上传失败";
          retobj["servemsg"] = ywmsg;
          this.outMethod.emit(retobj);
        }
      } else {
        // 使用默认服务
        this.commservice.handResponse("get", this.uploadurl, respbody, (arg1, resp, arg2) => {
          if (arg1) {
            const retobj = {
              fileId: "",
              filepath: "",
              flag: "",
              msg: '',
            };
            if (arg2) {
              const filearr = resp;
              if (filearr && filearr.length) {
                const fileobj = filearr[0];
                const fileId = fileobj.id;
                const filepath = fileobj.thumbPath;
                const filename = fileobj.originalName;
                retobj['fileId'] = fileId;
                retobj["filepath"] = filepath;
                retobj['flag'] = "success";
                retobj["filename"] = filename;
                retobj["msg"] = "上传成功";
                if (this.o.attachmentDefineId != 2) {
                  this.fileshow = true;
                }
                this.filepath = filepath;
              }
            } else {
              retobj['flag'] = "fail";
              retobj["msg"] = "上传失败";
              if (this.o.attachmentDefineId != 2) {
                this.fileshow = false;
              }
              this.filepath = "";
            }
            // 如果有返回的还需要根据返回处理
            this.outMethod.emit(retobj);
          } else {
            this.commservice.warn("上传文件", '签名失败', this.uploadurl);
          }
        });
      }
    } else {
      // 上传文件后获取服务器返回的数据错误
    }
  }

  /**
   * 1:参数处理
   * autoup
   * uploadurl
   * uploadForm
   * filepath
   * filelx
   * 2:附件是否回显
   * 3:进度还原
   * 4：附件警告信息还原
   * 5： 导入按钮控制还原
   *
   *
   */
  zjctr(): void {
    this.autoup = this.o.autoup;  //true---自动导入，  false--点击导入按钮导入
    if (this.o.addurl) {
      // 非默认的上传服务
      //1--上传路径
      //2--除了file外的表单参数
      this.uploadurl = this.o.addurl;
      this.uploadForm = this.o.addreqobj ? this.o.addreqobj : null;
    } else {
      // 使用默认的上传服务
      //1--上传路经，使用默认值
      //2--除了file外的表单参数 attachmentDefineId 的处理
      if (this.o.attachmentDefineId) {
        this.uploadForm.attachmentDefineId = this.o.attachmentDefineId;
      }
    }
    const zjlx = this.o.zjlx ? this.o.zjlx : "add";  // 非必填，默认是 add
    switch (zjlx) {
      case "add":
        // 上传文件
        if (this.o.addurl) {
          // 非默认的上传服务。不回显
          this.fileshow = false;
          this.filepath = "";
        } else {
          // 默认的上传服务
          //attachmentDefineId  =1 照片上传成功回显。   attachmentDefineId！=1 非照片上传成功后不回显
          if (this.uploadForm.attachmentDefineId == 1) {
            this.fileshow = false;
            this.filepath = "";
            this.filelx = "tp"; // 回显附件类型
          }
        }
        break;
      case "edite":
        // 编辑附件
        if (this.o.addurl) {
          // 非默认的上传服务，不回显
          this.fileshow = false;
          this.filepath = "";
        } else {
          // 默认的上传服务
          // /attachmentDefineId  =1 照片上传成功回显。   attachmentDefineId！=1 非照片上传成功后不回显
          if (this.uploadForm.attachmentDefineId == 1) {
            this.fileshow = true;
            this.filepath = this.o.filepath ? this.o.filepath : '';
            this.filelx = "tp"; // 回显附件类型
          }
        }
        break;
    }
    this.progressFlag = false; // 进度还原
    this.progressbarLeft = "0px";
    this.jdtext = "";
    this.warntextflag = false;  // 警告信息还原
    this.warntext = "";
    if (!this.o.autoup) {
      this.drbtnDisabled = true;
    }
  }

  /*
    接受父组件的参数
    autoup----【必填】 true 自动上传    false---有导入按钮
    addurl--------【非必填， 默认是 attachment/uploadAttachment 】  可选值：  上传文件的url
    addreqobj----【非必填,】 上传文件除了 文件外的额外参数
    attachmentDefineId----【非必填， 默认是 1（图片）】 可选值： 2---文件------------addurl没有传递使用 attachment/uploadAttachment的时候
    filealias----【非必填，默认file】 文件参数别名
    allowedFileType 【非必填，默认全部类型【】 -----上传文件类型的限制   application  image  video   audio   pdf  compress doc  xls  ppt
    limtsize 【非必填】---限制上传大小
    zjlx  【非必填，默认 add（上传）, 可选值 edite（编辑）】
    filepath 【非必填】---回显文件路径（编辑必填）
   */
  @Input() o: any;

  /**
   *
   * @type {EventEmitter<any>}
   */
  @Output() outMethod: EventEmitter<any> = new EventEmitter<any>();

  constructor(private itservice: MyhttpService,
    private commservice: CommService) {

  }

  ngOnInit() {
    this.zjctr();
    this.initUploader();
    this.initUploaderEvents();
  }

  ngOnChanges(changes: { [hs: string]: SimpleChange }) {
    const firstchange = changes.o.firstChange;
    if (!firstchange) {
      this.commservice.log('form-fileinput---ngOnChanges--o', this.o);
      this.commservice.log("form-fileinput---ngOnChanges", changes.o.currentValue === this.o);
      this.zjctr();
    }
  }
}
